package com.dikang.yygh.msm.controller;

import com.alibaba.excel.util.StringUtils;
import com.dikang.yygh.common.exception.YyghException;
import com.dikang.yygh.common.result.Result;
import com.dikang.yygh.common.result.ResultCodeEnum;
import com.dikang.yygh.msm.utils.RandomUtil;
import com.dikang.yygh.msm.service.MsmService;
import com.dikang.yygh.vo.msm.MsmVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/msm")
public class MsmApiController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    private static final String SEND_COUNT ="Send_count:";

    //发送手机验证码
    @GetMapping("send/{phone}")
    public Result sendCode(@PathVariable String phone) {
        // redis中存在数据说明已经发送过了
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            return Result.ok();
        }
        //发送次数限制
        String countStr = redisTemplate.opsForValue().get(SEND_COUNT+phone);
        if (!StringUtils.isEmpty(countStr)){
            int count = Integer.parseInt(countStr);
            if (count > 3){
                throw new YyghException(ResultCodeEnum.valueOf("超过了一天发送次数"));
            }
        }else {
            countStr="0";
        }

        // 如果redis中获取不到数据
        // 生成验证码
        code = RandomUtil.getSixBitRandom();
        // 通过调用Service，整合短信服务进行发送
        boolean isSend = msmService.send(phone, code);
        // 生成验证码到redis里面，设置有效时间
        if (isSend) {
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
            // 发送次数限制一天只能发5条
            Integer sendCount = Integer.parseInt(countStr) +1;
            redisTemplate.opsForValue().set(SEND_COUNT+phone,sendCount.toString(),24*60,TimeUnit.MINUTES);
            return Result.ok();
        } else {
            return Result.fail().message("发送短信失败");
        }

    }
    @GetMapping("MqListen")
    public Result sentMsg(MsmVo msmVo){
        msmService.send(msmVo);
        return Result.ok();
    }
}
